package com.ticket.web.controller.system;

import com.ticket.common.annotation.Log;
import com.ticket.common.constant.UserConstants;
import com.ticket.common.core.controller.BaseController;
import com.ticket.common.core.domain.AjaxResult;
import com.ticket.common.core.domain.entity.SysDept;
import com.ticket.common.enums.BusinessType;
import com.ticket.common.exception.base.BaseException;
import com.ticket.common.utils.Const;
import com.ticket.common.utils.StringUtils;
import com.ticket.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * 部门信息
 * 
 */
@Api(description = "部门信息")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        if ("admin".equals(getUsername())){
            SysDept sysDept = new SysDept();
            sysDept.setDeptType(0);
            return success(deptService.selectDeptList(sysDept));
        }
        return success(deptService.selectDeptLists(dept));
    }

    @ApiOperation("查询部门列表（排除节点）")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude")
    public AjaxResult excludeChild(@RequestParam Long deptId,@RequestParam Long operaId)
    {
        //是否存在上级部门
        SysDept parent = deptService.getParent(deptId);
        if (null == parent){
            return success(Collections.EMPTY_LIST);
        }
        SysDept sysDept = new SysDept();
        sysDept.setOperaId(operaId);
        List<SysDept> depts = deptService.selectDeptLists(sysDept);
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    @ApiOperation("根据部门编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }


    @ApiOperation("新增部门")
    @ApiImplicitParam(name = "dept",value = "部门实体",dataType = "SysDept",dataTypeClass = SysDept.class)
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    @ApiOperation("修改部门")
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        SysDept deptInfo = deptService.selectDeptById(deptId);
        if (!dept.getDeptName().equals(deptInfo.getDeptName())) {
            //剧院
            if (Const.ONE.equals(dept.getDeptType()) && deptService.checkDeptNameOpera(dept)) {
                return error("修改剧院'" + dept.getDeptName() + "'失败，剧院名称已存在");
            }
            if (Const.ZERO.equals(dept.getDeptType()) && deptService.checkDeptNameUnique(dept)) {
                SysDept sysDept = deptService.selectDeptById(deptId);
                if (!sysDept.getDeptName().equals(dept.getDeptName())) {
                    return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
                }
            }
        }
        if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该部门包含未停用的子部门！");
        }

        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    @ApiOperation("删除部门")
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        SysDept sysDept = deptService.selectDeptById(deptId);
        if (Const.ZERO.equals(sysDept.getDeptType())){
            //部门
            if (deptService.hasChildByDeptId(deptId))
            {
                return warn("存在下级部门,不允许删除");
            }
            if (deptService.checkDeptExistUser(deptId))
            {
                return warn("部门存在用户,不允许删除");
            }
        }else {
            //剧院
            if (deptService.hasChildByDeptId(deptId)){
                return warn("存在下级剧院或者部门,不允许删除");
            }
            if (deptService.checkDeptExistUser(deptId))
            {
                return warn("剧院存在用户,不允许删除");
            }
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    @ApiOperation("登录人剧院列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId",value = "当前登录人所在的部门id",dataType = "long",dataTypeClass = Long.class),
            @ApiImplicitParam(name = "child",value = "是否只查询子部门",dataType = "long",dataTypeClass = Long.class)
    })
    @GetMapping("/operaList")
    public AjaxResult operaList(Long deptId,Long child){
        if ("admin".equals(getUsername())){
            return success(deptService.operaList(null,null));
        }
        return success(deptService.operaList(deptId,child));
    }

    @ApiOperation("剧院列表")
    @GetMapping("/theatreList/forAllUser")
    public AjaxResult theatreList(){
        return success(deptService.theatreList());
    }

    @ApiOperation("演出获取剧院列表")
    @GetMapping("/operaByPlan")
    public AjaxResult operaByPlan(String keyName,Long child){
        if (null == getOperaId()){
            throw new BaseException("当前账号不属于剧院账号");
        }
        return success(deptService.operaByPlan(getOperaId(),keyName,child));
    }

    @ApiOperation("演出报表获取剧院列表")
    @GetMapping("/operaTableByPlan")
    public AjaxResult operaTableByPlan(String keyName,Long child){
        if (null == getOperaId()){
            throw new BaseException("当前账号不属于剧院账号");
        }
        return success(deptService.operaTableByPlan(getOperaId(),keyName,child));
    }

    @ApiOperation("获取剧院 （海报  小程序）")
    @ApiImplicitParam(name = "keyName",value = "模糊匹配字段",dataType = "String",dataTypeClass = String.class)
    @GetMapping("/getOperaList/forAllUser")
    public AjaxResult getOperaList(String keyName){
        return success(deptService.getOperaListAll(keyName));
    }

    @ApiOperation("小程序获取剧院详情")
    @ApiImplicitParam(name = "operaId",value = "剧院id",required = true,dataType = "Long",dataTypeClass = Long.class)
    @GetMapping("/getOperaInfo/forAllUser")
    public AjaxResult getOperaInfo(@RequestParam Long operaId){
        return success(deptService.getOperaInfo(operaId));
    }
}
